const co = require('co');
const OSS = require('ali-oss');
module.exports = class extends think.Service {
  constructor(ctx) {
    super(ctx);
  }
  // 初始化 
  async register(ctx, type) {
    const region = think.config('ext.alioss.region');
    const accessKeyId = think.config('ext.alioss.accessKeyId');
    const accessKeySecret = think.config('ext.alioss.accessKeySecret') || '';
    const client = new OSS({
      region,
      accessKeyId,
      accessKeySecret
    });

    const getAllFilesList = () => {
      const deferred = think.defer();
      co(function*() {
        client.useBucket('thinkadmin');
        var result = yield client.list();
        deferred.resolve(result);
      }).catch(function(err) {
        deferred.reject(err);
      });
      return deferred.promise;
    }

    return await getAllFilesList();
  }

  // 初始化 
  async getImage(ctx, type) {
    const region = think.config('ext.alioss.region');
    const accessKeyId = think.config('ext.alioss.accessKeyId');
    const accessKeySecret = think.config('ext.alioss.accessKeySecret') || '';
    const client = new OSS({
      region,
      accessKeyId,
      accessKeySecret
    });

    const getAllFilesList = () => {
      const deferred = think.defer();
      co(function*() {
        client.useBucket('thinkadmin');
        var result = yield client.list();
        deferred.resolve(result);
      }).catch(function(err) {
        deferred.reject(err);
      });
      return deferred.promise;
    };

    const getImageUrl = () => {
      return client.signatureUrl('6bec69456728971545a85f3055d3e2e7.jpeg');
    };

    return {
      getAllFilesList,
      getImageUrl
    };
  }

  async getStream(key) {
    co(function* () {
      var result = yield client.get('object-key', 'local-file');
      console.log(result);
    }).catch(function (err) {
      console.log(err);
    });
  }
};
